package cn.monkey.family.server.domain.shop.item;

import cn.monkey.family.data.Range;
import cn.monkey.family.data.crud.repository.QueryDslQueryRequestRepository;
import cn.monkey.family.data.shop.item.Item;
import cn.monkey.family.data.shop.item.ItemQueryRequest;
import cn.monkey.family.data.shop.item.QItem;
import com.google.common.base.Strings;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import org.springframework.data.repository.NoRepositoryBean;

import java.util.Optional;


@NoRepositoryBean
public interface ItemRepository extends QueryDslQueryRequestRepository<Item, String, ItemQueryRequest>,
        FindItemById {

    @Override
    Optional<Item> findById(String s);

    @Override
    default Predicate queryDslPredicate(ItemQueryRequest queryRequest) {
        QItem qItem = QItem.item;

        BooleanBuilder booleanBuilder = new BooleanBuilder();
        if (!Strings.isNullOrEmpty(queryRequest.getName())) {
            booleanBuilder.and(qItem.name.like(queryRequest.getName()));
        }
        String[] tags = queryRequest.getTags();
        if (tags != null) {
            booleanBuilder.and(qItem.tags.eq(tags));
        }
        String[] type = queryRequest.getType();
        if (type != null) {
            booleanBuilder.and(qItem.type.in(type));
        }

        Range<Double> priceRange = queryRequest.getPriceRange();
        if (priceRange != null) {
            Double min = priceRange.getMin();
            Double max = priceRange.getMax();
            if (min != null && max != null) {
                booleanBuilder.and(qItem.price.between(min, max));
            } else if (min != null) {
                booleanBuilder.and(qItem.price.goe(min));
            } else if (max != null) {
                booleanBuilder.and(qItem.price.loe(max));
            }
        }
        return booleanBuilder;
    }


}
